#include "BitReserve.h"

// read N bits from the bit stream
uint32 CBitReserve::hgetbits(uint32 N)
{
	totbit += N;

	uint32 val = 0;
	int32 j = N, k;

	while (j > 0)
	{
		if (buf_bit_idx == 0)
		{
			buf_bit_idx = 8;
			buf_byte_idx++;
		}

#pragma warning(disable:4018)
		k = (j < buf_bit_idx) ? j : buf_bit_idx;

		// BUFSIZE = 4096 = 2^12, so
		// buf_byte_idx%BUFSIZE == buf_byte_idx & 0xfff
		int32 tmp = buf[buf_byte_idx & 0xfff] & putmask[buf_bit_idx];
		buf_bit_idx -= k;
		tmp = tmp >> buf_bit_idx;
		j -= k;
		val |= tmp << j;
   }
   return val;
}

// read 1 bit from the bit stream
uint32 CBitReserve::hget1bit()
{
	totbit++;

	if (buf_bit_idx == 0)
	{
		buf_bit_idx = 8;
		buf_byte_idx++;
	}

	// BUFSIZE = 4096 = 2^12, so
	// buf_byte_idx%BUFSIZE == buf_byte_idx & 0xfff
	uint32 val = buf[buf_byte_idx & 0xfff] & putmask[buf_bit_idx];
	buf_bit_idx--;
	val >>= buf_bit_idx;

	return val;
}
